#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
用户ORM仓储

使用SQLAlchemy实现用户仓储接口
"""

from typing import List, Optional, Dict, Any
from app.utils.sqlalchemy_utils import SQLAlchemyRepository, get_session
from app.domains.user.interface import IUserRepository
from app.domains.user.model_orm import User
from app.utils.id_generator import IdGeneratorSingleton, UuidGenerator


class UserORMRepository(SQLAlchemyRepository, IUserRepository):
    """使用SQLAlchemy实现的用户仓储"""
    
    def __init__(self):
        """初始化仓储"""
        super(UserORMRepository, self).__init__(User)
    
    def get_by_username(self, username: str) -> Optional[User]:
        """根据用户名获取用户
        
        Args:
            username: 用户名
            
        Returns:
            User: 用户对象或None
        """
        with get_session() as session:
            return session.query(User).filter_by(username=username).first()
    
    def get_by_email(self, email: str) -> Optional[User]:
        """根据邮箱获取用户
        
        Args:
            email: 邮箱
            
        Returns:
            User: 用户对象或None
        """
        with get_session() as session:
            return session.query(User).filter_by(email=email).first()
    
    def update_token(self, user_id: str, token: str) -> bool:
        """更新用户令牌
        
        Args:
            user_id: 用户ID
            token: 令牌
            
        Returns:
            bool: 操作是否成功
        """
        with get_session() as session:
            user = session.query(User).filter_by(user_id=user_id).first()
            if user:
                user.token = token
                return True
            return False
    
    def batch_create(self, users: List[User]) -> List[User]:
        """批量创建用户
        
        Args:
            users: 用户列表
            
        Returns:
            List[User]: 创建成功的用户列表
        """
        # 获取现有的用户名、邮箱和用户ID
        existing_usernames = set()
        existing_emails = set()
        existing_user_ids = set()
        successful_users = []
        
        try:
            # 查询现有用户名、邮箱和用户ID
            with get_session() as session:
                username_results = session.query(User.username).all()
                for username in username_results:
                    existing_usernames.add(username[0])
                
                email_results = session.query(User.email).filter(User.email.isnot(None)).all()
                for email in email_results:
                    existing_emails.add(email[0])
                
                user_id_results = session.query(User.user_id).all()
                for user_id in user_id_results:
                    existing_user_ids.add(user_id[0])
        except Exception as e:
            print(f"获取现有用户信息失败(ORM): {str(e)}")
        
        # 分批处理，每批50个
        batch_size = 50
        for i in range(0, len(users), batch_size):
            batch_users = users[i:i+batch_size]
            valid_batch_users = []
            
            # 先检查所有用户的唯一约束
            for user in batch_users:
                try:
                    # 额外检查用户名和邮箱是否已存在
                    if user.username in existing_usernames:
                        print(f"批量创建用户失败（ORM）: 用户名已存在 - {user.username}")
                        continue
                    
                    if user.email and user.email in existing_emails:
                        print(f"批量创建用户失败（ORM）: 邮箱已存在 - {user.email}")
                        continue
                    
                    # 检查用户ID是否已存在
                    if user.user_id and user.user_id in existing_user_ids:
                        print(f"批量创建用户失败（ORM）: 用户ID已存在 - {user.user_id}")
                        continue
                    
                    # 记录用户ID已被使用
                    if user.user_id:
                        existing_user_ids.add(user.user_id)
                    
                    # 通过检查的用户添加到有效列表
                    valid_batch_users.append(user)
                    
                    # 记录用户名和邮箱已被使用
                    existing_usernames.add(user.username)
                    if user.email:
                        existing_emails.add(user.email)
                    
                except Exception as e:
                    print(f"批量创建用户检查失败（ORM）: {str(e)}")
            
            # 一次性处理整批有效用户
            if valid_batch_users:
                with get_session() as session:
                    try:
                        # 添加所有有效用户
                        for user in valid_batch_users:
                            session.add(user)
                        
                        # 一次性提交
                        session.flush()
                        
                        # 刷新所有用户以获取数据库生成的值
                        for user in valid_batch_users:
                            session.refresh(user)
                        
                        # 添加到成功列表
                        successful_users.extend(valid_batch_users)
                        
                    except Exception as e:
                        session.rollback()
                        print(f"批量创建用户批处理失败（ORM）: {str(e)}")
                        
                        # 如果批处理失败，回退到单个处理
                        for user in valid_batch_users:
                            try:
                                with get_session() as single_session:
                                    single_session.add(user)
                                    single_session.flush()
                                    single_session.refresh(user)
                                    successful_users.append(user)
                            except Exception as e2:
                                print(f"批量创建用户单个处理失败（ORM）: {str(e2)}")
        
        return successful_users 